<template>
  <div v-loading="loading" class="out_storage" element-loading-text="加载中...">
    <!-- <div class="m_l"> -->
    <el-form ref="formRef" inline-message :inline="true" :model="form" :rules="rules">
      <el-form-item label="出库单号前缀" prop="outboundCodePrefix">
        <el-input
          v-model.trim="form.outboundCodePrefix"
          class="input_code"
          maxlength="2"
          clearable
          placeholder="前缀名称"
        />
      </el-form-item>
      <el-form-item label="入库单号前缀" prop="inboundCodePrefix">
        <el-input
          v-model.trim="form.inboundCodePrefix"
          class="input_code"
          maxlength="2"
          clearable
          placeholder="前缀名称"
        />
      </el-form-item>
      <el-form-item label="旧件返仓">
        <div class="flex column-gap-5px">
          <!-- 仓库选择 -->
          <el-select-v2
            v-model="form.returnStoreId"
            placeholder="请选择仓库"
            :loading="getWarehouseOptionListLoading"
            filterable
            :filter-method="handleGetWarehouseOptionList"
            style="width: 140px"
            clearable
            :options="warehouseOptionListForSelectV2"
            @change="handleWarehouseOptionChange"
          />

          <!-- 仓位选择 -->
          <el-select
            v-if="getWarehousePositionState(form.returnStoreId)"
            v-model="form.returnStorePositionId"
            style="width: 140px"
            placeholder="请选择仓位"
            :loading="getWarehousePositionOptionListLoaing"
            filterable
            :filter-method="handleGetWarehousePositionOptionList"
            clearable
          >
            <el-option
              v-for="option in warehousePositionOptionList"
              :key="option.id"
              :label="option.name"
              :disabled="option.disabled"
              :value="option.id"
            />
          </el-select>
        </div>
      </el-form-item>
      <!-- <el-form-item label=" " class="checkbox-item" prop="outboundCodeRule">
          <el-checkbox-group v-model="form.outboundCodeRule">
            <el-checkbox value="1">六位出库日期</el-checkbox>
            <el-checkbox value="2">八位防伪码</el-checkbox>
            <el-checkbox value="3">六位随机防窜码</el-checkbox>
          </el-checkbox-group>
        </el-form-item> -->

      <!-- <div class="flex-align-center checkboxs mb10"> -->

      <!-- <el-form-item label=" " class="checkbox-item" prop="inboundCodeRule">
              <el-checkbox-group v-model="form.inboundCodeRule">
                <el-checkbox value="1">六位出库日期</el-checkbox>
                <el-checkbox value="2">八位防伪码</el-checkbox>
                <el-checkbox value="3">六位随机防窜码</el-checkbox>
              </el-checkbox-group>
            </el-form-item> -->
      <!-- </div> -->
      <!-- <el-form-item label="出库库存锁定策略" class="mb10">
            <el-radio-group v-model="form.stockLockStrategy" class="badge-sel">
              <el-radio :value="1" class="check_xy">
                <div class="text_xy">不锁定</div>
              </el-radio>
              <el-radio :value="2" class="check_xy">
                <div class="text_xy">创建状态</div>
              </el-radio>
              <el-radio :value="3" class="check_xy">
                <div class="text_xy">审核状态</div>
              </el-radio>
              <el-radio :value="4" class="check_xy">
                <div class="text_xy">出库状态</div>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="序列号">
            <div>
              <el-radio-group v-model="form.enableCode" class="badge-sel">
                <el-radio :value="true" class="check_xy">
                  <div class="text_xy">启用</div>
                </el-radio>
                <el-radio :value="false" class="check_xy">
                  <div class="text_xy">关闭</div>
                </el-radio>
              </el-radio-group>
              <p class="tips"
                >启用序列号后，仓库出入库和盘点调拨都需要执行扫码流程，精确控制物料</p
              >
            </div>
          </el-form-item> -->
    </el-form>
    <HPlainButton is-modal @click="saveSet(formRef)">保存</HPlainButton>
    <!-- <el-form class="m_l2">
          <el-form-item label="先入后出">
            <div>
              <el-radio-group v-model="form.firstInThenOut" class="badge-sel">
                <el-radio :value="true" class="check_xy">
                  <div class="text_xy">启用</div>
                </el-radio>
                <el-radio :value="false" class="check_xy">
                  <div class="text_xy">关闭</div>
                </el-radio>
              </el-radio-group>
              <div class="tips">启用序列号后，物料必须有入库记录后，才能出库</div>
            </div>
          </el-form-item>
          <el-form-item label="库存策略">
            <div>
              <el-radio-group v-model="form.stockStrategy" class="badge-sel">
                <el-radio :value="1" class="check_xy">
                  <div class="text_xy">有库存才可下单</div>
                </el-radio>
                <el-radio :value="2" class="check_xy">
                  <div class="text_xy">无需库存可下单</div>
                </el-radio>
              </el-radio-group>
              <div class="tips">当前库存数是否足够的时候，允许下单和发货</div>
            </div>
          </el-form-item>
          <el-form-item label="库存负数">
            <div>
              <el-radio-group v-model="form.stockNegative" class="badge-sel">
                <el-radio :value="1" class="check_xy">
                  <div class="text_xy">可为负库存</div>
                </el-radio>
                <el-radio :value="2" class="check_xy">
                  <div class="text_xy">不能为负库存</div>
                </el-radio>
              </el-radio-group>
              <div class="tips">库存负数关系到库存不够的时候是否可以发货</div>
            </div>
          </el-form-item>
        </el-form> -->
    <!-- </div> -->
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { getStorerSet, saveStoreSet } from '@/api/basic'
  import { useGetAllWarehouseOptionList } from '@/services/pages/storage/useWarehouse'
  import _ from 'lodash'
  import { useGetWarehousePositionOptionList } from '@/services/pages/storage/useWarehouseOut'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const {
    optionList: warehouseOptionList,
    getOptionListParam: getWarehouseOptionListParam,
    getOptionListLoading: getWarehouseOptionListLoading,
    getOptionList: getWarehouseOptionList,
  } = useGetAllWarehouseOptionList()
  const {
    warehousePositionOptionList,
    getWarehousePositionOptionListParam,
    getWarehousePositionOptionListLoaing,
    getWarehousePositionOptionList,
  } = useGetWarehousePositionOptionList()

  // 适用于虚拟选择器的仓库下拉列表
  const warehouseOptionListForSelectV2 = computed(() => {
    return warehouseOptionList.value.map((item) => {
      return {
        label: item.name,
        value: item.id,
        disabled: item.disabled,
      }
    })
  })

  const loading = ref(false)
  const props = defineProps({
    active_name: String,
  })

  const form = reactive({
    enableCode: false,
    firstInThenOut: false,
    id: null,
    inboundCodePrefix: 'RK',
    inboundCodeRule: [],
    outboundCodePrefix: 'CK',
    outboundCodeRule: [],
    stockLockStrategy: 1,
    stockNegative: 2,
    stockStrategy: 1,
    returnStoreId: '',
    returnStorePositionId: '',
  })

  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    outboundCodePrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    outboundCodeRule: [
      { required: true, message: '请选择组合类型', trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (form.outboundCodeRule.length < 2) {
            callback(new Error('至少选择两种组合类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    inboundCodePrefix: [
      { required: true, message: '请输入前缀', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,2}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    inboundCodeRule: [
      { required: true, message: '请选择组合类型', trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (form.inboundCodeRule.length < 2) {
            callback(new Error('至少选择两种组合类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  })

  /**
   * 仓库下拉选项搜索事件
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehouseOptionList = _.debounce((keyword: string) => {
    if (getWarehouseOptionListParam.value.name !== keyword) {
      getWarehouseOptionListParam.value.name = keyword
      getWarehouseOptionListParam.value.id = ''
      getWarehouseOptionList()
    }
  }, 600)

  /**
   * 仓位下拉选项搜索事件
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehousePositionOptionList = _.debounce(
    (keyword: string, warehouseOptionId: string) => {
      if (getWarehousePositionOptionListParam.value.name !== keyword) {
        getWarehousePositionOptionListParam.value.name = keyword
        getWarehousePositionOptionList(warehouseOptionId)
      }
    },
    600,
  )

  /**
   * 获取仓位启用状态
   * @param {String} warehouseOptionId - 仓库id
   */
  const getWarehousePositionState = (warehouseOptionId: string) => {
    const warehouseOption = warehouseOptionList.value.find((item) => item.id === warehouseOptionId)
    if (warehouseOption) {
      return warehouseOption.enableStorePosition
    }
    return false
  }

  /**
   * 仓库选择事件
   */
  const handleWarehouseOptionChange = () => {
    const warehousePositionStatus = getWarehousePositionState(form.returnStoreId)
    if (warehousePositionStatus) {
      getWarehousePositionOptionList(form.returnStoreId)
    }
  }

  // 获取仓库序列号设置
  const getCodeSet = async () => {
    loading.value = true
    await getStorerSet().then((res) => {
      const {
        enableCode,
        firstInThenOut,
        id,
        inboundCodePrefix,
        outboundCodePrefix,
        returnStoreId,
        returnStorePositionId,
      } = res.data.data.row
      form.enableCode = enableCode
      form.firstInThenOut = firstInThenOut
      form.id = id
      form.inboundCodePrefix = inboundCodePrefix
      // form.inboundCodeRule = res.data.data.row.inboundCodeRule.split(',')
      form.outboundCodePrefix = outboundCodePrefix
      form.returnStoreId = returnStoreId === '0' ? '' : returnStoreId
      form.returnStorePositionId = returnStorePositionId === '0' ? '' : returnStorePositionId
      // form.outboundCodeRule = res.data.data.row.outboundCodeRule.split(',')
      // form.stockLockStrategy = res.data.data.row.stockLockStrategy
      // form.stockNegative = res.data.data.row.stockNegative
      // form.stockStrategy = res.data.data.row.stockStrategy
    })
    loading.value = false
  }

  // 保存仓库序列号设置
  const saveSet = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        const data = {
          codeActiveMode: 1,
          enableCode: form.enableCode,
          firstInThenOut: form.firstInThenOut,
          id: form.id,
          inboundCodePrefix: form.inboundCodePrefix,
          // inboundCodeRule: form.inboundCodeRule.join(),
          outboundCodePrefix: form.outboundCodePrefix,
          returnStoreId: form.returnStoreId,
          returnStorePositionId: form.returnStorePositionId,
          // outboundCodeRule: form.outboundCodeRule.join(),
          // stockLockStrategy: form.stockLockStrategy,
          // stockNegative: form.stockNegative,
          // stockStrategy: form.stockStrategy,
        }
        ElMessageBox({
          type: 'warning',
          title: '提示',
          message: `确认保存修改的设置?`,
          showCancelButton: true,
          closeOnClickModal: false,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '加载中...'
              setTimeout(() => {
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 0)
              }, 1000)
            } else {
              done()
            }
          },
        }).then(async () => {
          await saveStoreSet(data).then((res) => {
            if (res.data.success) {
              HMessage.success('更新设置成功')
            } else {
              HMessageBox.error(res.data.message)
            }
          })
          getCodeSet()
        })
      } else {
        return
      }
    })
  }

  onMounted(async () => {
    if (props.active_name == 'code') {
      await getCodeSet()
    }
    getWarehouseOptionList()
  })

  defineExpose({ getCodeSet })
</script>

<style scoped lang="scss">
  .out_storage {
    display: flex;
    justify-content: space-between;
    align-items: center;

    :deep(.el-form) {
      .el-form-item {
        .el-form-item__label {
          height: 28px;
          line-height: 28px;
        }

        .el-form-item__content {
          .el-input {
            width: 160px;
          }
        }
      }
    }
  }
</style>
